#coding:utf-8
import re,logging,os
import wsgiref.handlers
import string
import StringIO
import urllib

from functools import wraps
from google.appengine.api import images
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users
from loginTool import login_required
import methods
from models import Images
from django.utils import simplejson
from google.appengine.api.images import Image

def format_date(dt):
    return dt.strftime('%a, %d %b %Y %H:%M:%S GMT')

class PublicPage(webapp.RequestHandler):
  def render(self, template_file, template_value):
      path = os.path.join(os.path.dirname(__file__), template_file)
      self.response.out.write(template.render(path, template_value))
  def returnjson(self,dit):
      self.response.headers['Content-Type'] = "application/json"
      self.response.out.write(simplejson.dumps(dit))

class PhotoList(PublicPage):
  @login_required
  def get(self,page):
        index=0 if page=="" else int(page)
        images=methods.getAllImages(index)
        prev,next=methods.getPageing(len(images), index)
        template_value={"images":images[:16],"prev":prev,"next":next}
        self.render('html/photoManage/photoInfoList.html', template_value)

class PhotoInfo(PublicPage):
  @login_required
  def get(self,page):
        searchType = self.request.get('searchType')
        radio = self.request.get('radio')
        findDegree = self.request.get('findDegree')
#        template_value = {'searchType':searchType,'radio':radio,'findDegree':findDegree,'page':page,}
        self.redirect("/photoInfoList/%s?radio=%s&findDegree=%s&searchType=%s" %(page,radio,findDegree,searchType))
#        self.render('template/photo/photoInfo.html', template_value)
#        self.render('html/photoManage/photoInfo.html', template_value)

class PhotoInfoList(PublicPage):
  @login_required
  def get(self,page):
        searchType = self.request.get('searchType')
        radio = self.request.get('radio')
        findDegree = self.request.get('findDegree')
    
        index=0 if page=="" else int(page)

        if (radio == 'imageId' or radio == ''):
            if (findDegree == '1' or findDegree == ''):
                if (searchType ==''):
                    images = methods.getAllImages(index)
                    prev,next=methods.getPageing(len(images), index)
                    template_value={"images":images[:16],"prev":prev,"next":next,"index":index,'searchType':searchType,'radio':radio,'findDegree':findDegree}
                    self.render('template/photo/photoInfo.html', template_value)
#                    self.render('html/photoManage/photoInfoList.html', template_value)
                else:
                    image = methods.getImage(searchType)
                    template_value={"images":[image],'searchType':searchType,'radio':radio,'findDegree':findDegree}
                    self.render('template/photo/photoInfo.html', template_value)
#                    self.render('html/photoManage/photoInfoList_1.html', template_value)
#                    self.render('html/photoManage/photoInfoList_1.html', template_value)
            elif (findDegree == '2'):
                if (searchType ==''):
                    images = methods.getAllImages(index)
                    prev,next=methods.getPageing(len(images), index)
                    template_value={"images":images[:16],"prev":prev,"next":next,"index":index,'searchType':searchType,'radio':radio,'findDegree':findDegree}
                    self.render('template/photo/photoInfo.html', template_value)
#                    self.render('html/photoManage/photoInfoList.html', template_value)
                else:
                    #searchType = db.Key(int(searchType))
                    #images = Entity.Gql("Where __key__=:1" ,searchType)
                    images = db.GqlQuery("SELECT * FROM Images Where photoCode>=:1 AND photoCode<=:2" ,searchType,u""+searchType+"" + u"\ufffd")
                    template_value={"images":images,'searchType':searchType,'radio':radio,'findDegree':findDegree}
                    self.render('template/photo/photoInfo.html', template_value)
#                    self.render('html/photoManage/photoInfoList.html', template_value)
        if (radio == 'imageName'):
            if (findDegree == '1'):
                if (searchType ==''):
                    images = methods.getAllImages(index)
                    prev,next=methods.getPageing(len(images), index)
                    template_value={"images":images[:16],"prev":prev,"next":next,"index":index,'searchType':searchType,'radio':radio,'findDegree':findDegree}
                    self.render('template/photo/photoInfo.html', template_value)
#                    self.render('html/photoManage/photoInfoList.html', template_value)
                else:
                    images = db.GqlQuery("SELECT * FROM Images Where name=:1" ,searchType)
                    template_value={"images":images,'searchType':searchType,'radio':radio,'findDegree':findDegree}
                    self.render('template/photo/photoInfo.html', template_value)
#                    self.render('html/photoManage/photoInfoList.html', template_value)
            elif (findDegree == '2'):
                if (searchType ==''):
                    images = methods.getAllImages(index)
                    prev,next=methods.getPageing(len(images), index)
                    template_value={"images":images[:16],"prev":prev,"next":next,"index":index,'searchType':searchType,'radio':radio,'findDegree':findDegree}
                    self.render('template/photo/photoInfo.html', template_value)
#                    self.render('html/photoManage/photoInfoList.html', template_value)
                else:
                    images = db.GqlQuery("SELECT * FROM Images Where name>=:1 AND name<=:2" ,searchType,u""+searchType+"" + u"\ufffd")
                    template_value={"images":images,'searchType':searchType,'radio':radio,'findDegree':findDegree}
                    self.render('template/photo/photoInfo.html', template_value)
#                    self.render('html/photoManage/photoInfoList.html', template_value)
  @login_required
  def post(self,page):
        radio = self.request.get('radio')
        findDegree = self.request.get('findDegree')
        searchType = self.request.get('searchType')
        self.redirect('/photoInfoList/0?searchType=%s&findDegree=%s&radio=%s' %(searchType,findDegree,radio))

class PhotoInfoUpdate(PublicPage):
  @login_required
  def get(self):
        id = string.atoi(self.request.get('image_id'))
        index = self.request.get('page_id')
        if index=="":
            index='0'
        index = string.atoi(index)
        image = methods.getImage(id)
        template_value={"image":image,"index":index,}
        self.render('template/photo/photoInfoUpdate.html', template_value)
#        self.render('html/photoManage/photoInfoUpdate.html', template_value)
  @login_required
  def post(self):
        id = string.atoi(self.request.get('image_id'))
        index = self.request.get('page_id')
        if index=="":
            index='0'
        index = string.atoi(index)
        image = methods.getImage(id)
        newName = self.request.get('imageName')
        if image.name != newName:
            photoLib_Photos = db.GqlQuery("SELECT * FROM PhotoLib_Photo WHERE photoCode=:1",image.photoCode)
            for photoLib_Photo in photoLib_Photos:
                if photoLib_Photo.photoCode:
                    #photoLib_Photo.status = '1'#把图库里的图片状态改为1
                    db.put(photoLib_Photo)
        image.name = newName
        image.description = self.request.get('description')
        image.photoLibName = self.request.get('photoLib')
        image.put()
        self.redirect('/photoInfoList/%d' %index)
        
class ShowImage(PublicPage):
  @login_required
  def get(self,id):
        image=methods.getImage(id)
        if not image:return self.error(404)
        template_value={"image":image,}
        self.render('template/photo/show.html', template_value)
#        self.render('html/photoManage/show.html', template_value)

class GetImage(PublicPage):
   @login_required
   def get(self,size,id):
        dic=self.request.headers
        name = self.request.get("name")
        if name:
            image1=methods.getImage(id)
            image1.name = name
            image1.photoCode = id
            image1.put()
        key=dic.get("If-None-Match")
        self.response.headers['ETag']=size+id
        if key and key==size+id:
            return self.error(304)
        image=methods.downImage(id, size)
        if not image or not image.bf:
            return self.error(404)
#        self.response.headers['Content-Type'] = 'image/jpeg'
        self.response.headers['Content-Type'] = str(image.mime) 
        self.response.headers['Cache-Control']="max-age=315360000"
        self.response.headers['Last-Modified']=format_date(image.date)
        self.response.out.write(image.bf)

class photoUpload(PublicPage):
    @login_required
    def get(self):
        self.render('template/photo/upload2.html', {})
#        self.render('html/photoManage/upload2.html', {})
    @login_required
    def post(self):
        dit={"result":"error"}
        bf=self.request.get("Filedata")
        name = self.request.get("filename")
        if not bf:
            return self.returnjson(dit)
        image=methods.addImage2(bf,name)
#        image=Image(bf)
        if not image:
             return self.returnjson(dit)
        dit["result"]="ok"
        dit["id"]=image.id
        dit["name"]=name
        return self.returnjson(dit)

class download(webapp.RequestHandler):
    @login_required
    def get(self):
        id = string.atoi(self.request.get('image_id'))
        image = methods.getImage(id)
        if image and image.bf:
#            img = images.Image(image.bf)
#            fileType = image.filetype
#            img.im_feeling_lucky()
           
#            if fileType == 'image/jpeg':
#                thumbnail = img.execute_transforms(output_encoding=images.JPEG)
#                filename = '%s.jpg' %id
#            if fileType == 'image/gif':
#                thumbnail = image.bf
#                filename = '%s.gif' %id
#            if fileType == 'image/bmp':
#                thumbnail = img.execute_transforms(output_encoding=images.JPEG)
#                filename = '%s.bmp' %id
#            if fileType == 'image/png':
#                thumbnail = img.execute_transforms(output_encoding=images.PNG)
#                filename = '%s.png' %id
            if image.filetype:
                self.response.headers['Content-Type'] = image.filetype
            else:
                self.response.headers['Content-Type'] = "application/x-www-form-urlencoded"
            self.response.headers['Content-Disposition'] = 'attachment;filename=%s' %image.name.encode('utf-8')

            self.response.out.write(image.bf)

#            self.response.out.write(image.bf)
        else:
            self.error(404)
#            return thumbnail

class Delete_Image_ID(PublicPage):
    @login_required
    def get(self,id):
        ##更新图片库中的图片信息
        images = methods.getImage(id)
        photoLib_Photos = db.GqlQuery("SELECT * FROM PhotoLib_Photo WHERE photoCode=:1",images.photoCode)
        for photoLib_Photo in photoLib_Photos:
            if photoLib_Photo.photoCode:
                photoLib_Photo.status = '0'#把图库里的图片状态改为2
                db.put(photoLib_Photo)
        ##删除图片
        methods.delImageByid(id)
        self.redirect('/photoInfo/0')

class DeletePhotoInfo(PublicPage):
    @login_required
    def get(self,id):
        methods.delImageByid(id)
        self.redirect('/photoInfoList/0')
